package com.gxa.modules.service.accessservice.impl;

import com.gxa.common.R;
import com.gxa.common.utils.MD5Utils;
import com.gxa.component.jwt.JwtUtils;
import com.gxa.modules.mapper.accessmapper.LoginMapper;
import com.gxa.modules.pojo.User;
import com.gxa.modules.service.accessservice.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R login(String loginName, String password) {
        R<Object> r = new R<>();
        String newPassword= MD5Utils.encrypt(password,MD5Utils.MD5_KEY);
        User user=loginMapper.selectPasswordByLoginName(loginName);
        r.setCode(500);
        r.setMsg("用户名或密码错误");
        if(user!=null&&user.getPassword().equals(newPassword)) {
            r.setCode(200);
            r.setMsg("登录成功");
            String token= JwtUtils.createToken(UUID.randomUUID().toString(),"gxa",loginName,JwtUtils.TTMILLIS);
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            redisTemplate.setKeySerializer(stringRedisSerializer);
            redisTemplate.setValueSerializer(stringRedisSerializer);
            redisTemplate.opsForValue().set(loginName,token,1, TimeUnit.DAYS);
            r.setData(token);
        }
        return r;
    }

    @Override
    public R loginOut(String loginName) {
        R r = new R();

        redisTemplate.delete(loginName);
        r.setCode(200);
        r.setMsg("退出登录成功！");
        return r;
    }
}
